package books4africa

class FulfillmentException extends RuntimeException{
	String message
	String list
}

class FulfillmentService {

	def inventoryService
	def emailService
	
    def createFulfillment(params){
		
		def req = BookRequest.get(params.id)
		
		def donations = new Donation()
		donations = Donation.executeQuery("select inv from Donation donat, Inventory inv where inv.donation = donat and inv.qty > 0 and donat.book = :book", [book: req.book])
	   
		if (!req){
			throw new FulfillmentException(
				message:"Can't access the requests for the title ${params.title}",
				list: req.errors.each{println it}
			)
		}
		
		//if (!donations){
		//	throw new FulfillmentException(
		//		message: "Can't access the donations for the book ${params.title}",
		//		list: donations.errors.each{println it}	
		//	)
	//	}
						
		[bookRequestInstance: req, donationInstanceList: donations]
		
	}
	
	def saveFulfillment(params){
		
		def donation = Donation.get(params.id)
		
		// udpate donation filled qty
		donation.bookQtyFilled = params.qtyFilled.toInteger()
		donation.save()
		
		// check filled qty with book request qty to determine if request has been fulfilled
		def bookRequest = BookRequest.get(params.bookRequestId)
		int tempQty = bookRequest.bookQty
		int filledQty = params.qtyFilled.toInteger()
		
		// if equal zero out requested qty and set fulfilled date
		if (tempQty == filledQty)
		{
			bookRequest.bookQty = 0
			bookRequest.dateFulfilled = new Date()
			
			// send out notification
			emailService.emailDonor(bookRequest, donation)
		}
		else	// update books left to request
		{
			tempQty = tempQty - filledQty
			bookRequest.bookQty = tempQty
		}
		// save request
		bookRequest.save()
		
		def fulfillment = new Fulfillment(
			shipQty: params.qtyFilled,
			donation: donation,
			shipDate: new Date(),
			requests: bookRequest
		).save(flush:true, failOnError:true)
		
		
		if (!fulfillment){
			throw new FulfillmentException(
				message: "Couldn't create a new Fulfillment notification",
				list: fulfillment.errors.each{println it}
			)
		}
		if (!donation){
			throw new FulfillmentException(
				message: "Couldn't access the donation record",
				list: donation.errors.each{println it}
			)
		}
		
		inventoryService.removeFromInventory(donation, params.qtyFilled.toInteger())
		
	}
}
